//
//  BRInviteViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2022/1/18.
//  Copyright © 2022 Brezze GWG. All rights reserved.
//

#import "BRInviteViewController.h"
#import "BRInviteHeaderView.h"
#import "BRInviteCodeView.h"
#import "BRInviteRewardViewController.h"
#import "BRInviteHistoryViewController.h"
#import "BRInvitePopView.h"
#import "BRInviteRewardModel.h"

@interface BRInviteViewController ()<QMUITextFieldDelegate>
{
    QMUITextField *_inviteCodeTF;
}
@property (nonatomic,strong) BRInviteHeaderView *headerView;

@property (nonatomic,strong) BRInviteCodeView *inviteView;

//@property (nonatomic,strong) BRInviteCodeView *inviteInputView;

@property (nonatomic,strong) UIScrollView *myScrollView;

@property (nonatomic,strong) BRInvitePopView *invitePopView;

@property (nonatomic,strong) QMUIButton *inviteBtn;

@end

@implementation BRInviteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    [self blockAction];
    
    [self requestRule];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    BRInviteModel *model = [BROpenURL br_inviteCode];
    if (model.inviteCode.length != 0){
        NSString *invStr = [BRUserManager share].userModel.inviteCode;
        if ([[model.inviteCode uppercaseString] isEqualToString:invStr]) {
            //不能填写自己的邀请码
//            [BRHud showAuto:@"不能填写自己的邀请码" inView:self.view];
            return;
        }
//        self.inviteInputView.inputStr = model.inviteCode;
        [self.myScrollView jk_scrollToBottomAnimated:NO];
    }
}

#pragma mark - request --
- (void)requestInvite:(NSString *)code {
//    WS(weakSelf);
    NSString *invStr = [BRUserManager share].userModel.inviteCode;
    if ([[code uppercaseString] isEqualToString:invStr]) {
        //不能填写自己的邀请码
        [BRHud showAuto:Localized(@"invite_inviteSelfErr") inView:self.view];
        return;
    }
    [[BRRequestManager shared] GET:[BRAPI inviteCode:[code uppercaseString]] params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        
        NSLog(@"code = %@",dataDict[@"data"]);
        [BRHud showAutoSuccInView:self.view];

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
    }];
    
}

- (void)requestRule {
    
    [[BRRequestManager shared] GET:[BRAPI inviteReward] params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSLog(@"reward -- %@",dataDict);
        
        NSArray *arr = [BRInviteRewardModel mj_objectArrayWithKeyValuesArray:dataDict[@"data"]];
        [self br_setRewar:arr];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
    }];
    
}

- (void)br_setRewar:(NSArray *)arr {
    
    if (arr.count == 0) return;
    
    NSString *point = @"";
    NSString *coupon = @"";
    BRInviteRewardModel *dto = arr.firstObject;
    if (dto.rewardList.count == 0) return;
    BRRewardModel *model = dto.rewardList.firstObject;
    NSArray *all = [model.type componentsSeparatedByString:@","];
    NSMutableArray *rewardArr = [NSMutableArray array];
    for (NSString *typeStr in all) {
        
        /// 奖励类型：1-积分 2-优惠券 3-余额
        if (typeStr.integerValue == 1) {
            point = [NSString stringWithFormat:@"%ld %@",model.point,Localized(@"points_points")];
            [rewardArr addObject:[NSString stringWithFormat:@"%@: %ld",Localized(@"points_points"),model.point]];
        }else if (typeStr.integerValue == 2) {
            // 抵扣类型：1-金额 2-时间 3-折扣
            NSInteger couponType = model.couponInfo.deductionType;
            NSString *title2 = [BRStringTools br_couponsTypeStr:couponType];
            NSString *text2 = [BRStringTools br_couponsTypeContentV2:model.couponInfo.deduction];
            
            coupon = [NSString stringWithFormat:@"%@ %@",title2,text2];
            NSString *couponStr = [NSString stringWithFormat:@"%@: %@",Localized(@"menu_coupon"),coupon];
            if (model.quantity > 1) {
                couponStr = [NSString stringWithFormat:@"%@ * %ld",couponStr,model.quantity];
            }
            [rewardArr addObject:couponStr];
        }
        
    }
//    self.invitePopView.titleL.text = [NSString stringWithFormat:Localized(@"invite_ruleText"),model.inviteeNum];
    self.invitePopView.textL.text = [rewardArr componentsJoinedByString:@" & "];
    [self.invitePopView br_text:Localized(@"points_points") hidden:point.length == 0 by:0];
    [self.invitePopView br_text:Localized(@"menu_coupon") hidden:coupon.length == 0 by:1];
    
    
}


#pragma mark - action --
- (void)blockAction {
    WS(weakSelf);
    self.inviteView.inviteClickBlock = ^(NSInteger index, NSString * _Nonnull codeStr) {
        
        [weakSelf inviteDo:index value:codeStr];
    };
    
//    self.inviteInputView.inviteClickBlock = ^(NSInteger index, NSString * _Nonnull codeStr) {
//        
//        [weakSelf inviteDo:index value:codeStr];
//    };
    
    self.inviteView.toAboutBlock = ^{
        [weakSelf.invitePopView show];
    };
}

- (void)toSaveInviteCode {
    
    NSString *valueStr = _inviteCodeTF.text;
    valueStr = [valueStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    BOOL enable = [BRTools checkIsInviteCode:valueStr];
    if (!enable) {
        [BRHud showAuto:Localized(@"toast_validInviteCode") inView:self.view];
        return;
    }
    
    [self requestInvite:valueStr];
}


- (void)inviteDo:(NSInteger)index value:(NSString *)valueStr {
    
    switch (index) {
//        case 0:{
////            [self submitCode:valueStr];
//            [self requestInvite:valueStr];
//
//            break;
//        }
//        case 2:{
//            BRInviteHistoryViewController *vc = [[BRInviteHistoryViewController alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//            break;
//        }
        
        case 1:{
            [self inviteShare:valueStr];
            break;
        }
        case 3:{
            BRInviteRewardViewController *vc = [[BRInviteRewardViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        
        default:
            break;
    }
    
}

- (void)toRecord {
    BRInviteHistoryViewController *vc = [[BRInviteHistoryViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)inviteShare:(NSString *)code {
   
    NSString *inviteUrl = USERManager.invitationUrl;
    if (inviteUrl.length == 0) {
        inviteUrl = BASE_URL;
    }
    NSString *la = [[BRLanguageManager share].requestStr lowercaseString];
    if ([inviteUrl rangeOfString:@"?"].location != NSNotFound) {
        inviteUrl = [NSString stringWithFormat:@"%@&invitefriend=%@&lang=%@",inviteUrl,self.inviteView.codeStr,la];
    } else {
        inviteUrl = [NSString stringWithFormat:@"%@?invitefriend=%@&lang=%@",inviteUrl,self.inviteView.codeStr,la];
    }
    NSURL *shareUrl = [NSURL URLWithString:inviteUrl]; 
    // **'s invite code
    NSString * shareTitle = Localized(@"invite_inviteFriend");
    /*
     必须要提供url 才会显示分享标签否则只显示图片，部分分享的图片是分享链接H5的第一图
     */
    UIImage *iconImage = [UIImage imageNamed:@"AppLogo"];
    NSArray *activityItems = @[shareTitle,
                               shareUrl,
                               iconImage];
    
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:@[]];
    
    activityVC.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
        if (completed) {
            [BRHud showTips:Localized(@"public_success")];
        }
    };
    [self presentViewController:activityVC animated:YES completion:nil];
    
}



#pragma mark - textField delegate --
- (void)textFieldDidChangeSelection:(UITextField *)textField {
    
//    _submitBtn.enabled = [BRTools checkIsInviteCode:textField.text];
    
    if (textField.text.length >= 8) {
//        [textField resignFirstResponder];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([string isEqualToString:@""]) {
        return YES;
    }
    return [BRTools checkIsNumberABC:string];
//    return [BRTools canInputText:string];
}

- (void)valueChange:(QMUITextField *)textF {
    
    if (textF == _inviteCodeTF) {
        _inviteBtn.enabled = textF.text.length > 7;
    }
}

#pragma mark - SET UI --
- (void)setUI {
    
    [self br_createTop:Localized(@"invite_referral")];
    
    CGFloat mW = kScreenWidth / 2 - 28;
    QMUIButton *rightBtn = [[QMUIButton alloc] init];
    [rightBtn setTitle:Localized(@"invite_referralRecord") forState:UIControlStateNormal];
    [rightBtn setTitleColor:UIColorMakeWithHex(@"#9BBB55") forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont fontM:14];
//    rightBtn.titleLabel.numberOfLines = 0;
    rightBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self.navView.topView addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kNavH);
        make.bottom.offset(0);
        make.right.offset(-28);
        make.width.mas_equalTo(mW -20);
    }];
    [rightBtn addTarget:self action:@selector(toRecord) forControlEvents:UIControlEventTouchUpInside];
    
    UIScrollView *sView = [[UIScrollView alloc] init];
    sView.showsVerticalScrollIndicator = NO;
    [self.view insertSubview:sView atIndex:0];
    [sView  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(kSafeAreaTopHeight);
        make.bottom.left.right.equalTo(self.view);
        
    }];
    self.myScrollView = sView;
    [sView addSubview:self.headerView];
    [sView addSubview:self.inviteView];
    
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(0);
    }];
    [self.inviteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 32);
        make.top.equalTo(self.headerView.mas_bottom).offset(12);
        make.left.offset(16);
        make.right.offset(-16);
    }];
    
    QMUILabel *inviteTextL = [BRToolsView br_label:Localized(@"invite_codeEnter") textColor:kColorTitle font:[UIFont fontS:17] textAlignment:NSTextAlignmentLeft];
    inviteTextL.numberOfLines = 0;
    [sView addSubview:inviteTextL];
    [inviteTextL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.top.equalTo(self.inviteView.mas_bottom).offset(20);
    }];
    
    QMUITextField *inviteCodeTF = [[QMUITextField alloc] init];
    inviteCodeTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    inviteCodeTF.clearButtonPositionAdjustment = UIOffsetMake(-98, 0);
    inviteCodeTF.textInsets = UIEdgeInsetsMake(0, 14, 0, 98);
    inviteCodeTF.placeholderColor = UIColorMakeWithHex(@"#AAAAAC");
    inviteCodeTF.font = [UIFont fontM:14];
    inviteCodeTF.textColor = kColorTitle;
    inviteCodeTF.tintColor = kColorMain;
    inviteCodeTF.placeholder = Localized(@"shop_pleaseEnter");
    inviteCodeTF.delegate = self;
    inviteCodeTF.maximumTextLength = 8;
    [sView addSubview:inviteCodeTF];
    inviteCodeTF.layer.cornerRadius = 10;
    inviteCodeTF.layer.masksToBounds = YES;
    inviteCodeTF.backgroundColor = kColorBGEC;
    [inviteCodeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth - 40);
        make.height.mas_equalTo(44);
        make.centerX.offset(0);
        make.top.equalTo(inviteTextL.mas_bottom).offset(10);
        make.bottom.offset(-(28+ kSafeAreaBottomHeight));
    }];
    _inviteCodeTF = inviteCodeTF;
    [inviteCodeTF addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventEditingChanged];
    
    QMUIButton *inviteBtn = [[QMUIButton alloc] init];
    [inviteBtn setTitle:Localized(@"invite_save") forState:UIControlStateNormal];
    [inviteBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [inviteBtn setBackgroundColor:kColorMain];
    inviteBtn.titleLabel.font = [UIFont fontS:12];
    [inviteCodeTF addSubview:inviteBtn];
    [inviteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(88);
        make.top.right.offset(0);
       
    }];
    inviteBtn.enabled = NO;
    [inviteBtn addTarget:self action:@selector(toSaveInviteCode) forControlEvents:UIControlEventTouchUpInside];
    _inviteBtn = inviteBtn;
    [self.view addSubview:self.invitePopView];;
  
}

- (BRInviteHeaderView *)headerView {
    if (_headerView == nil) {
        _headerView = [[BRInviteHeaderView alloc] init];
    }
    return _headerView;
}

- (BRInviteCodeView *)inviteView {
    if (_inviteView == nil) {
        _inviteView = [[BRInviteCodeView alloc] initCodeInviteView];
    }
    return _inviteView;
}

//- (BRInviteCodeView *)inviteInputView {
//    if (_inviteInputView == nil) {
//        _inviteInputView = [[BRInviteCodeView alloc] initCodeView];
//    }
//    return _inviteInputView;
//}

- (BRInvitePopView *)invitePopView {
    if (_invitePopView == nil) {
        _invitePopView = [[BRInvitePopView alloc] init];
        _invitePopView.frame = self.view.bounds;
    }
    
    return _invitePopView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
